<?php

namespace App\Console\Commands;

use App\Events\EmailEvent;
use App\Events\Event;
use App\Events\WechatEvent;
use App\Model\Foundation\Student;
use App\Model\Foundation\Teacher;
use App\Model\System\Notice;
use App\Model\System\NoticeConfig;
use App\Model\Wechat\WechatUser;
use Illuminate\Console\Command;


/**
 * 每5分钟启动一次
 * Class Sender
 * @package App\Console\Commands
 */
class Sender extends Command
{
    protected $signature = 'Notice:Sender';

    protected $description = 'message sender';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        echo "start: \n";
        try{
            $notices = $this->getMessage();
            foreach ($notices as $notice){
                $this->send($notice);
                $this->remove($notice);
            }
        }catch (\Exception $e){
            $this->logger($e);
        }
        echo "end. \n";
    }


    /**
     * 获取要发送的notice列表
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    protected function getMessage()
    {
        $objs = Notice::all();
        return $objs;
    }


    /**
     * 获取消息提醒配置信息
     * @param $notice
     * @throws
     * @return array
     */
    protected function getNoticeConfig($notice)
    {
        try{
            $userid = $notice->to;
            $user = Student::where('userid', $userid)->first();
            if($user){
                $config = NoticeConfig::where('uid', $user->studentuid)
                    ->first();
            }else{
                $user = Teacher::where('userid', $userid)->first();
                $config = NoticeConfig::where('uid', $user->teacheruid)
                    ->first();
            }

            if(empty($user) || empty($config)){
                throw new \Exception("数据不全");
            }
            return [$user->toarray(), $config->toarray()];
        }catch (\Exception $e){
            throw $e;
        }
    }


    /**
     * 删除某条信息
     * @param Notice $notice
     * @return bool|null
     */
    protected function remove(Notice $notice)
    {
        return $notice->delete();
    }


    /**
     * 发送消息
     * @param $config
     * @param $notice
     * @return bool
     */
    protected function send($notice)
    {
        try{
            list($user, $config) = $this->getNoticeConfig($notice);

            if($config['byemail'] and $user['email']){
                $this->byEmail($user['email'], $notice);
            }
            if($config['bymessage'] and $user['mobile']){
                $this->byMessage($user['mobile'], $notice);
            }
            if($config['bywechat']){
                $wechat = WechatUser::where('userid', $notice['to'])
                        ->first();
                if($wechat){
                    $this->byWechat($wechat->openid, $notice);
                }
            }
            return true;
        }catch (\Exception $e){
            echo $e->getMessage();
            return false;
        }
    }


    /**
     * 发送短信消息
     * @param $number
     * @param $notice
     */
    protected function byMessage($number, $notice)
    {
        # todo 暂时不需要
    }

    /**
     * 发送微信消息
     * @param $openid
     * @param $notice
     */
    protected function byWechat($openid, $notice)
    {
        if($notice instanceof Notice){
            $notice = $notice->toarray();
        }
        if($notice['jsonable'] == 1){
            $note = json_decode($notice['body']);
            $obj = new WechatEvent($note, $openid, Event::NOTICE);
        }else{
            if($notice['jsonable'] == 2){
                $note = json_decode($notice['body']);
                $obj = new WechatEvent($note, $openid, Event::TASK);
            }else{
                $obj = new WechatEvent($notice['body'], $openid);
            }
        }
        event($obj);
    }

    /**
     * 发送邮件消息
     * @param $email
     * @param $notice
     */
    protected function byEmail($email, $notice)
    {
        if($notice instanceof Notice){
            $notice = $notice->toarray();
        }
        ## 发送上课通知
        if($notice['jsonable'] == 1){
            $content = json_decode($notice['body']);
            $notice['body'] = $content->username.": 您好，
            您报名参加的：".$content->coursename." 将于".$content->date."开课，特此通知.";
        }
        ## 发送作业通知
        if($notice['jsonable'] == 2){
            $content = json_decode($notice['body']);
            $notice['body'] = $content->title.
                " 时间：".$content->time.
                " 科目".$content->coursename.
                " 作业简介：".$content->task_title.
                " 作业详情：".$content->task_detail.
                " 备注：".$content->remark;
        }
        $email = new EmailEvent($email, $notice['title'], $notice['body']);
        event($email);
    }


    /**
     * 记录日志
     * @param \Exception $e
     */
    protected function logger(\Exception $e)
    {
        echo $e->getMessage();
    }

}
